package com.strato.rule.core.v1_0_0.execution;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.HashMap;
import java.util.Map;

import org.osgi.framework.Bundle;

import com.strato.rule.core.v1_0_0.annotation.RuleFunction;
import com.strato.rule.core.v1_0_0.annotation.RuleParam;

public class Rule {
	
	private Method method;

	private Class<?> clazz;

	private Object owner;

	private Bundle bundle;
	
	public Object getOwner() {
		return owner;
	}

	public Bundle getBundle() {
		return bundle;
	}

	public Class<?> getClazz() {
		return clazz;
	}

	public String getId() {
		return method.getAnnotation(RuleFunction.class).id();
	}
	
	public String getDisplay(){
		return method.getAnnotation(RuleFunction.class).display();
	}

	public Method getMethod() {
		return method;
	}

	public Rule(Object owner, Bundle bundle, Class<?> clazz, Method method){
		this.owner=owner;
		this.clazz=clazz;
		this.method=method;
		this.bundle=bundle;
		compile();
	}
	
	private void compile(){
	}
	
	public Map<String,Object> describe(){
		Map<String,Object> map=new HashMap<String,Object>();
		RuleFunction ruleFunction = method.getAnnotation(RuleFunction.class);
		String id=ruleFunction.id();
		String display=ruleFunction.display();
		String group=ruleFunction.group();
		map.put("id", id);
		map.put("display", display);
		map.put("group", group);
		Map<String,Map<String,Object>> paramDetails=new HashMap<String,Map<String,Object>>();
		Parameter[] params = method.getParameters();
		if(params!=null){
			for(Parameter p:params){
				RuleParam ruleParamAnnotation = p.getAnnotation(RuleParam.class);
				if(ruleParamAnnotation==null){
					continue;
				}
				String editor=ruleParamAnnotation.editor();
				String text=ruleParamAnnotation.text();
				String paramName=p.getName();
				Map<String,Object> paramDescribe=new HashMap<String,Object>();
				paramDescribe.put("editor", editor);
				paramDescribe.put("name", paramName);
				paramDescribe.put("text", text);
				paramDetails.put(paramName, paramDescribe);
			}
		}
		map.put("params", paramDetails);
		return map;
	}

//	private static Set<String> extractRuleParamNames(String display) {
//		Set<String> rpns=new LinkedHashSet<String>();
//		Matcher m = pattern.matcher(display);
//		while(m.find()){
//			String matched=m.group();
//			String ruleParamName=matched.substring(1,matched.length()-1);
//			rpns.add(ruleParamName);
//		}
//		return rpns;
//	}
//	
//	static Pattern pattern = Pattern.compile("\\{[a-zA-Z0-9\\._]*\\}");
	
}
